package com.filepublic.demo.server.service.impl;

import com.filepublic.demo.common.constant.ExceptionConstant;
import com.filepublic.demo.common.context.ThreadLocalContext;
import com.filepublic.demo.common.exception.BaseLogicException;
import com.filepublic.demo.pojo.dto.PenPalDto;
import com.filepublic.demo.pojo.entity.PenPalEntity;
import com.filepublic.demo.pojo.entity.UserEntity;
import com.filepublic.demo.pojo.query.UserBaseQuery;
import com.filepublic.demo.pojo.vo.PenPalVo;
import com.filepublic.demo.server.mapper.PenPalBaseMapper;
import com.filepublic.demo.server.mapper.UserBaseMapper;
import com.filepublic.demo.server.service.PenPalService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PenPalServiceImpl implements PenPalService {

    @Resource
    PenPalBaseMapper penPalBaseMapper;

    @Resource
    UserBaseMapper userBaseMapper;


    /**
     * 获取笔友信息
     * @return
     */
    @Override
    public List<PenPalVo> penPalInfo() {
        //查询笔友信息
        String userId = ThreadLocalContext.getCurrentId();
        List<PenPalVo> penPalVo = penPalBaseMapper.selectPenPal(userId);

        return penPalVo;
    }

    /**
     * 添加笔友
     * @param penPalDto
     */
    @Override
    @Transactional
    public void penPalAdd(PenPalDto penPalDto) {
        //查询有无笔友的用户信息
        UserEntity userEntity = userBaseMapper.selectUserById(penPalDto.getPenPalId());

        if(userEntity == null){
            throw new BaseLogicException(ExceptionConstant.NO_USER);
        }

        String userId = ThreadLocalContext.getCurrentId();

        PenPalEntity penPalEntity = PenPalEntity.builder()
                .penPalOwnerId(userId)
                .penPalId(penPalDto.getPenPalId())
                .penPalName(penPalDto.getPenPalName())
                .build();
        //插入数据
        penPalBaseMapper.insertPenPal(penPalEntity);
    }
}
















